package com.itheima.logdemo.utils;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 日志切面
 */
@Aspect
@Component
public class LogAspect {
    
    private final static Logger logger = LoggerFactory.getLogger("kafka");
    
    /**
     * 凡是打过LogInfo注释的均会被拦截
     */
    @Pointcut("@annotation(com.itheima.logdemo.utils.LogInfo)")
    public void log() {
    }
    
    /**
     * 环绕通知
     */
    @Around(value = "log()")
    public Object arround(ProceedingJoinPoint pjp) {
        try {
            MethodSignature signature = (MethodSignature) pjp.getSignature();
            String className = pjp.getTarget().getClass().getSimpleName();
            String methodName = signature.getName();
            
            LogUtil.log("before " + className + "." + methodName);
            
            //方法执行
            long start = System.currentTimeMillis();
            Object o = pjp.proceed();
            long end = System.currentTimeMillis();
            
            //耗时统计，message以cost开头的日志
            LogUtil.cost("cost:" + className + "." + methodName, end - start);
            
            LogUtil.log("after " + className + "." + methodName);
            
            return o;
        } catch (Throwable e) {
            e.printStackTrace();
            return null;
        }
        
    }
    
}
